package com.cjq.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cjq.auth.exception.ServiceException;
import com.cjq.auth.remote.UserRemoteService;
import com.cjq.auth.service.AuthService;
import com.cjq.common.constants.JwtConstants;
import com.cjq.common.constants.TokenConstants;
import com.cjq.common.domain.User;
import com.cjq.common.domain.request.UserReq;
import com.cjq.common.domain.response.UserRes;
import com.cjq.common.result.Result;
import com.cjq.common.utils.JwtUtils;
import com.cjq.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private UserRemoteService userRemoteService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;

    @Override
    public UserRes accountLogin(UserReq userReq) {
        if (StringUtils.isBlank(userReq.getUserName())){
            throw new ServiceException("账号不能为空");
        }
        if (StringUtils.isBlank(userReq.getUserPwd())){
            throw new ServiceException("密码不能为空");
        }
        Result<User> user = userRemoteService.findUser(userReq.getUserName());
        User data = user.getData();
        if (data==null){
            throw new ServiceException("用户不存在，去注册");
        }
        if (!userReq.getUserPwd().equals(data.getUserPwd())){
            throw new ServiceException("密码错误");
        }
        HashMap<String, Object> map = new HashMap<>();
        String userKey = UUID.randomUUID().toString().replaceAll("-", "");
        map.put(JwtConstants.USER_KEY,userKey);
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey, JSONObject.toJSONString(data),15, TimeUnit.MINUTES);
        UserRes userRes = new UserRes();
        userRes.setToken(token);
        userRes.setTime(TokenConstants.TOKEN_EXPIRATION_TIME_STR);
        return userRes;
    }

    @Override
    public User userInfo() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String userJSONStr = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        return JSONObject.parseObject(userJSONStr,User.class);
    }

    @Override
    public void logout() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        redisTemplate.delete(TokenConstants.LOGIN_TOKEN_KEY + userKey);
    }
}
